from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, DateTime, Integer
from datetime import datetime
from pydantic import BaseModel, ConfigDict
from typing import Optional, Union
from enum import Enum
from decimal import Decimal

__all__ = ['Base']

# 数据库模型基类
Base = declarative_base()


def empty_to_none(v: str) -> Optional[str]:
    if v == '':
        return None
    return v


def str_validator(v: any):
    if isinstance(v, str):
        if isinstance(v, Enum):
            return v.value
        else:
            return v
    elif isinstance(v, (float, int, Decimal)):
        # is there anything else we want to add here? If you think so, create an issue.
        return str(v)
    elif isinstance(v, (bytes, bytearray)):
        return v.decode()
    else:
        raise Exception("PydanticTypeError")


class EmptyStrToNone(str):
    @classmethod
    def __get_validators__(cls):
        yield str_validator
        yield empty_to_none


class TimestampMixin:
    create_time = Column(DateTime, comment='创建时间', default=datetime.now())
    creator = Column(Integer, default=0, comment='创建者')
    updater = Column(Integer, default=0, comment='更新者')
    update_time = Column(DateTime, comment='更新时间', default=datetime.now())
    remark = Column(String(255), comment='备注')


class BasePageObject(BaseModel):
    page: int = 1
    limit: int = 10
    order: str = ''
    asc: bool = False


class SchemaBase(BaseModel):
    model_config = ConfigDict(use_enum_values=True)
